package de.gwtprime.client.views.popup;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.widgets.helper.InfoPopup;
import de.gwtprime.shared.requestFactory.User2Proxy;
import de.gwtprime.shared.requestFactory.request.User2Request;

public class ChangePrivateWithdrawAddress extends PopupPanel {

	private static ChangePrivateWithdrawAddressUiBinder uiBinder = GWT
			.create(ChangePrivateWithdrawAddressUiBinder.class);

	interface ChangePrivateWithdrawAddressUiBinder extends
			UiBinder<Widget, ChangePrivateWithdrawAddress> {
	}
	
	@UiField TextBox addressBox;
	@UiField Button saveBtn;

	public ChangePrivateWithdrawAddress(final ClientFactory clientFactory) {
		setWidget(uiBinder.createAndBindUi(this));
		
		setAutoHideEnabled(true);
		setGlassEnabled(true);
		
		String address = clientFactory.getUser().getPrivateWithdrawAddress();
		addressBox.setText(address == null ? "" : address);
		addressBox.getElement().setPropertyString("placeholder", "Deine Adresse");
		
		saveBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				User2Request userRequest = clientFactory.getRequestFactory().userRequest();
				
				final User2Proxy user = userRequest.edit(clientFactory.getUser());
				
				user.setPrivateWithdrawAddress(addressBox.getText());
				userRequest.persist().using(user).fire(new Receiver<Long>() {

					@Override
					public void onSuccess(Long response) {
						ChangePrivateWithdrawAddress.this.hide();
						new InfoPopup("Gespeichert").center();
						clientFactory.setUser(user);
						
						clientFactory.getNotificationCenter().showMessage("Private Adresse wurde geändert");
					}
				});
			}
		});
	}
}
